#include <iostream>
#include <vector>
#include <queue>
#include <limits>
#include <utility>

using namespace std;

const int INF = numeric_limits<int>::max();

using Graph = vector<vector<pair<int, int>>>;

vector<int> dijkstra(const Graph& graph, int start) 
{
    int n = graph.size();
    vector<int> dist(n, INF);
    dist[start] = 0;

    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.push({0, start});

    while (!pq.empty()) 
    {
        int u = pq.top().second;
        int d = pq.top().first;
        pq.pop();

        if (d > dist[u]) continue;

        for (const auto& edge : graph[u]) 
        {
            int v = edge.first;
            int weight = edge.second;

            if (dist[u] + weight < dist[v]) 
            {
                dist[v] = dist[u] + weight;
                pq.push({dist[v], v});
            }
        }
    }

    return dist;
}

Graph buildGraph(const vector<pair<pair<int, int>, int>>& edges, int numVertices)
{
    Graph graph(numVertices);
    for (const auto& edge : edges) 
    {
        int u = edge.first.first;
        int v = edge.first.second;
        int weight = edge.second;

        graph[u].emplace_back(v, weight);
        graph[v].emplace_back(u, weight);
    }
    return graph;
}

int main() 
{
    int numVertices;
    cout << "请输入图的顶点数量: ";
    cin >> numVertices;

    int numEdges;
    cout << "请输入图的边的数量: ";
    cin >> numEdges;

    vector<pair<pair<int, int>, int>> edges;
    cout << "请输入每条边的信息（格式：r1 r2 weight）:" << endl;
    for (int i = 0; i < numEdges; ++i) 
    {
        int r1, r2, weight;
        cin >> r1 >> r2 >> weight;
        edges.emplace_back(make_pair(r1, r2), weight);
    }

    int startVertex;
    cout << "请输入起始顶点: ";
    cin >> startVertex;

    Graph graph = buildGraph(edges, numVertices);

    vector<int> dist = dijkstra(graph, startVertex);

    // 输出最短路径
    cout << "从顶点 " << startVertex << " 到其他顶点的最短路径长度:" << endl;
    for (int i = 0; i < numVertices; ++i) 
    {
        if (dist[i] == INF) {
            cout << "到顶点 " << i << " 的最短路径长度: 无穷大" << endl;
        } 
        else 
        {
            cout << "到顶点 " << i << " 的最短路径长度: " << dist[i] << endl;
        }
    }

    return 0;
}